package com.bdmc.system.listener;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.bdmc.base.domain.BaseDevice;
import com.bdmc.base.domain.BasePerson;
import com.bdmc.base.domain.vo.BaseDeviceImportVo;
import com.bdmc.base.service.IBaseDeviceService;
import com.bdmc.base.service.IBasePersonService;
import com.bdmc.common.excel.ExcelListener;
import com.bdmc.common.excel.ExcelResult;
import com.bdmc.common.exception.ServiceException;
import com.bdmc.common.utils.LoginUtils;
import com.bdmc.common.utils.spring.SpringUtils;
import com.bdmc.system.service.ISysConfigService;
import lombok.extern.slf4j.Slf4j;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 系统用户自定义导入
 *
 * @author HuangLu
 */
@Slf4j
public class BasePersonImportListener extends AnalysisEventListener<BaseDeviceImportVo>
        implements ExcelListener<BaseDeviceImportVo> {

    private final IBasePersonService personService;

    private final IBaseDeviceService deviceService;
    private final Boolean isUpdateSupport;

    private final Long deptId ;

    private int successNum = 0;
    private int failureNum = 0;
    private final StringBuilder successMsg = new StringBuilder();
    private final StringBuilder failureMsg = new StringBuilder();

    public BasePersonImportListener() {
        String initPassword = SpringUtils.getBean(ISysConfigService.class).selectConfigByKey("sys.user.initPassword");
        this.personService = SpringUtils.getBean(IBasePersonService.class);
        this.deviceService =  SpringUtils.getBean(IBaseDeviceService.class);
        this.isUpdateSupport = false;
        this.deptId = LoginUtils.getDeptId();
    }

    @Override
    public void invoke(BaseDeviceImportVo userVo, AnalysisContext context) {
        LambdaQueryWrapper<BasePerson> w = Wrappers.lambdaQuery();
        w.eq(BasePerson::getPersonName,userVo.getPersonName()).eq(BasePerson::getMobile,userVo.getMobile());
        BasePerson person = this.personService.getOne(w);

        LambdaQueryWrapper<BaseDevice> w1 = Wrappers.lambdaQuery();
        w1.eq(BaseDevice::getDevicePhoneNum,userVo.getDevicePhoneNum());
        BaseDevice device = this.deviceService.getOne(w1);
        LocalDateTime now = LocalDateTime.now();
        try {
            // 验证是否存在这个用户
            if (person==null) {
                person = BeanUtil.toBean(userVo, BasePerson.class);
                person.setDeptId(deptId);
                person.setPersonType("cleaning_and_sanitation");
                if(device==null){
                    device = new BaseDevice();
                    device.setDeptId(deptId);
                    device.setDeviceName("工牌");
                    device.setDeviceType("work_card");
                    device.setDevicePhoneNum(userVo.getDevicePhoneNum());
                    device.setSimNum(userVo.getSimNum());
                    device.setImei(userVo.getDevicePhoneNum());
                    device.setManufacturer("HXW");
                    device.setDeviceModel("A60");
                    deviceService.save(device);
                }
                person.setDeviceId(device.getDeviceId());

                personService.save(person);
                successNum++;
                successMsg.append("<br/>").append(successNum).append("、人员 ").append(person.getPersonName()).append(" 导入成功");
            }  else {
                failureNum++;
                failureMsg.append("<br/>").append(failureNum).append("、人员  ").append(person.getPersonName()).append(" 已存在");
            }
        } catch (Exception e) {
            failureNum++;
            String msg = "<br/>" + failureNum + "、人员 " + userVo.getPersonName() + " 导入失败：";
            failureMsg.append(msg).append(e.getMessage());
            log.error(msg, e);
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {

    }

    @Override
    public ExcelResult<BaseDeviceImportVo> getExcelResult() {
        return new ExcelResult<BaseDeviceImportVo>() {

            @Override
            public String getAnalysis() {
                if (failureNum > 0) {
                    failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
                    throw new ServiceException(failureMsg.toString());
                } else {
                    successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
                }
                return successMsg.toString();
            }

            @Override
            public List<BaseDeviceImportVo> getList() {
                return null;
            }

            @Override
            public List<String> getErrorList() {
                return null;
            }
        };
    }
}
